#include "PrecompiledHeaders.h"
#include "ReplayRecorder.h"

ReplayRecorder::ReplayRecorder()
{
    recording = false;
}

ReplayRecorder::~ReplayRecorder()
{
}

/*
 * Start a new replay
 */
void ReplayRecorder::begin()
{
    if(recording) {
        fprintf(stderr, "Warning: Recording in progress\n");
        return;
    }
    gravityStates.clear();
    recording = true;
}

/*
 * Add a new input state to the recording, specifying the 
 * time since the last entry and the relative input positions
 */
void ReplayRecorder::addNewInputState(Ogre::Real time, Ogre::Vector3 gravity)
{
    GravityState current;
    current.time = time;
    current.gravity = gravity;
    gravityStates.push_back(current);
}

/*
 * End the current replay
 */
void ReplayRecorder::end()
{
    if(!recording) {
        fprintf(stderr, "Error: No replay to end\n");
        return;
    }
    GravityState current;
    current.time = 10;
    current.gravity = Ogre::Vector3(0, -50, 0);
    recording = false;
}

std::vector<GravityState> ReplayRecorder::getReplay()
{
    if(recording) throw new Ogre::Exception(1234, "Replay has not been finished", "ReplayRecorder::getReplay");
    return gravityStates;
}

/*
 * Write the current replay to a file, returns the filename for future 
 */
std::string ReplayRecorder::save()
{
    if(recording) {
        fprintf(stderr, "Warning: cannot save while recording\n");
        return NULL;
    }
    char random[11];
    std::string filename = "";
    filename.append(REPLAYS_DIRECTORY);
    filename.append(randomString(random, REPLAY_FILENAME_LENGTH));
    filename.append(".replay");
    file.open(filename.c_str(), std::ios::out | std::ios::binary);
    for(unsigned int  i=0; i<gravityStates.size(); i++) {
        file.write((char *)&gravityStates[i], sizeof(GravityState));
    }
    file.close();
    //printf("Saved %i bytes to %s\n", gravityStates.size()*sizeof(GravityState), filename.c_str());
    return filename;
}

void ReplayRecorder::restart()
{
    gravityStates.clear();
}
